package com.yzf.enterprise.common.utils.ip;

import com.fasterxml.jackson.databind.JsonNode;
import com.yzf.enterprise.common.utils.JacksonUtil;
import com.yzf.enterprise.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.yzf.enterprise.common.utils.http.HttpUtils;

/**
 * 获取地址类
 *
 * @author china
 */
public class AddressUtils {
    private static final Logger log = LoggerFactory.getLogger(AddressUtils.class);

    public static final String IP_URL = "http://ip.taobao.com/service/getIpInfo.php";

    public static String getRealAddressByIP(String ip) {
        String address = "XX XX";
        // 内网不查询
        if (IpUtils.internalIp(ip)) {
            return "内网IP";
        }
        String rspStr = HttpUtils.sendPost(IP_URL, "ip=" + ip);
        if (StringUtils.isEmpty(rspStr)) {
            log.error("获取地理位置异常 {}", ip);
            return address;
        }
        try {
            JsonNode data = JacksonUtil.getMapper().readTree(rspStr).get("data");
            if (data!=null){
                JsonNode region = data.get("region");
                JsonNode city = data.get("city");
                if (region!=null&&city!=null){
                    address = region.textValue() + " " + city.textValue();
                }
            }
        } catch (Exception e) {
            log.error("AddressUtils|getRealAddressByIP|[ip]:{}", e);
        }
        return address;
    }

}
